<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="survey-title">问卷统计分析：{{ surveyData.title }}</span>
        <el-button style="float: right; margin-left: 10px" type="primary" size="small" icon="el-icon-arrow-left" @click="goBack">返回列表</el-button>
        <el-button style="float: right;" type="success" size="small" icon="el-icon-download" @click="exportStats">导出报表</el-button>
      </div>
      
      <div v-loading="loading">
        <!-- 基本信息 -->
        <div class="survey-info">
          <div class="info-item">
            <div class="info-label">问卷标题</div>
            <div class="info-value">{{ surveyData.title }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">问卷描述</div>
            <div class="info-value">{{ surveyData.description }}</div>
          </div>
          <div class="info-grid">
            <div class="info-item">
              <div class="info-label">开始时间</div>
              <div class="info-value">{{ parseTime(surveyData.startTime) }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">结束时间</div>
              <div class="info-value">{{ parseTime(surveyData.endTime) }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">访问数量</div>
              <div class="info-value">{{ surveyData.visitCount || 0 }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">回答数量</div>
              <div class="info-value">{{ surveyData.answerCount || 0 }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">提交率</div>
              <div class="info-value">{{ visitCount > 0 ? Math.round(answerCount / visitCount * 100) + '%' : '0%' }}</div>
            </div>
          </div>
        </div>
        
        <el-divider content-position="left">问题统计</el-divider>
        
        <!-- 问题统计 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>
        <div v-else-if="!surveyData.questions || surveyData.questions.length === 0" class="empty-data">
          暂无问题数据
        </div>
        <div v-else class="question-stats">
          <div class="question-item" v-for="(question, index) in surveyData.questions" :key="index">
            <div class="question-header">
              <span class="question-title">{{ index + 1 }}. {{ question.title }}</span>
              <span class="question-type">{{ questionTypeMap[question.type] }}</span>
            </div>
            
            <!-- 单选题统计 -->
            <div v-if="question.type === 'radio'" class="chart-container">
              <div class="chart" ref="radioChart" :id="'radioChart' + index"></div>
              <div class="stat-table">
                <el-table :data="formatOptionsStats(question.optionsStats)" border size="small">
                  <el-table-column prop="label" label="选项" min-width="120" />
                  <el-table-column prop="count" label="票数" width="80" align="center" />
                  <el-table-column prop="percent" label="占比" width="100" align="center" />
                </el-table>
              </div>
            </div>
            
            <!-- 多选题统计 -->
            <div v-if="question.type === 'checkbox'" class="chart-container">
              <div class="chart" ref="checkboxChart" :id="'checkboxChart' + index"></div>
              <div class="stat-table">
                <el-table :data="formatOptionsStats(question.optionsStats)" border size="small">
                  <el-table-column prop="label" label="选项" min-width="120" />
                  <el-table-column prop="count" label="票数" width="80" align="center" />
                  <el-table-column prop="percent" label="占比" width="100" align="center" />
                </el-table>
              </div>
            </div>
            
            <!-- 评分题统计 -->
            <div v-if="question.type === 'rate'" class="chart-container">
              <div class="rate-stats">
                <div class="rate-avg">
                  <span class="rate-label">平均分</span>
                  <el-rate
                    v-model="question.averageScore"
                    disabled
                    show-score
                    text-color="#ff9900"
                  />
                </div>
                <div class="chart" ref="rateChart" :id="'rateChart' + index"></div>
              </div>
            </div>
            
            <!-- 填空题统计 -->
            <div v-if="question.type === 'text'" class="text-stats">
              <div class="text-stats-header">
                <span>答卷数量：{{ question.answerCount || 0 }}</span>
              </div>
              <div class="text-answers">
                <div v-for="(answer, answerIndex) in question.textAnswers" :key="answerIndex" class="text-answer-item">
                  <span class="text-answer-index">{{ answerIndex + 1 }}</span>
                  <span class="text-answer-content">{{ answer }}</span>
                </div>
                <div v-if="!question.textAnswers || question.textAnswers.length === 0" class="empty-answers">
                  暂无回答
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getSurveyQuestionnaire } from "@/api/system/survey";
import * as echarts from 'echarts';

export default {
  name: "SurveyStatistics",
  data() {
    return {
      loading: true,
      surveyId: null,
      surveyData: {},
      chartInstances: [],
      questionTypeMap: {
        'radio': '单选题',
        'checkbox': '多选题',
        'text': '填空题',
        'rate': '评分题'
      }
    };
  },
  computed: {
    visitCount() {
      return this.surveyData.visitCount || 0;
    },
    answerCount() {
      return this.surveyData.answerCount || 0;
    }
  },
  created() {
    this.surveyId = this.$route.query.surveyId;
    this.getSurveyData();
  },
  methods: {
    /** 获取问卷数据 */
    getSurveyData() {
      this.loading = true;
      getSurveyQuestionnaire(this.surveyId).then(response => {
        this.surveyData = response.data;
        this.loading = false;
        this.$nextTick(() => {
          this.initCharts();
        });
      });
    },
    /** 返回问卷列表 */
    goBack() {
      this.$router.push('/system/survey/index');
    },
    /** 导出统计报表 */
    exportStats() {
      this.$modal.msgSuccess("导出成功");
    },
    /** 格式化选项统计数据 */
    formatOptionsStats(optionsStats) {
      if (!optionsStats) return [];
      return optionsStats.map(item => {
        return {
          label: item.label,
          count: item.count,
          percent: item.percent + '%'
        };
      });
    },
    /** 初始化图表 */
    initCharts() {
      // 销毁之前的图表实例
      this.chartInstances.forEach(chart => {
        chart.dispose();
      });
      this.chartInstances = [];
      
      // 初始化新的图表
      if (this.surveyData.questions && this.surveyData.questions.length > 0) {
        this.surveyData.questions.forEach((question, index) => {
          if (question.type === 'radio' || question.type === 'checkbox') {
            this.initPieChart(question, index, question.type);
          } else if (question.type === 'rate') {
            this.initRateChart(question, index);
          }
        });
      }
    },
    /** 初始化饼图 */
    initPieChart(question, index, type) {
      if (!question.optionsStats || question.optionsStats.length === 0) return;
      
      const chartDom = document.getElementById(type + 'Chart' + index);
      if (!chartDom) return;
      
      const myChart = echarts.init(chartDom);
      this.chartInstances.push(myChart);
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: question.optionsStats.map(item => item.label)
        },
        series: [
          {
            name: question.title,
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: question.optionsStats.map(item => {
              return {
                name: item.label,
                value: item.count
              };
            })
          }
        ]
      };
      
      myChart.setOption(option);
      
      // 响应式处理
      window.addEventListener('resize', function() {
        myChart.resize();
      });
    },
    /** 初始化评分图表 */
    initRateChart(question, index) {
      if (!question.optionsStats || question.optionsStats.length === 0) return;
      
      const chartDom = document.getElementById('rateChart' + index);
      if (!chartDom) return;
      
      const myChart = echarts.init(chartDom);
      this.chartInstances.push(myChart);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: question.optionsStats.map(item => item.label + '分'),
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '评分分布',
            type: 'bar',
            barWidth: '60%',
            data: question.optionsStats.map(item => item.count)
          }
        ]
      };
      
      myChart.setOption(option);
      
      // 响应式处理
      window.addEventListener('resize', function() {
        myChart.resize();
      });
    }
  },
  beforeDestroy() {
    // 销毁图表实例
    this.chartInstances.forEach(chart => {
      chart.dispose();
    });
    
    // 移除事件监听
    window.removeEventListener('resize', this.resizeHandler);
  }
};
</script>

<style lang="scss" scoped>
.survey-title {
  font-size: 18px;
  font-weight: bold;
}

.survey-info {
  margin-bottom: 20px;
  
  .info-item {
    margin-bottom: 10px;
    
    .info-label {
      font-weight: bold;
      margin-bottom: 5px;
    }
    
    .info-value {
      color: #606266;
    }
  }
  
  .info-grid {
    display: flex;
    flex-wrap: wrap;
    margin-top: 15px;
    
    .info-item {
      width: 200px;
      margin-right: 20px;
    }
  }
}

.question-stats {
  .question-item {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
    
    .question-header {
      margin-bottom: 15px;
      
      .question-title {
        font-size: 16px;
        font-weight: bold;
      }
      
      .question-type {
        margin-left: 10px;
        padding: 2px 8px;
        font-size: 12px;
        border-radius: 10px;
        background-color: #ecf5ff;
        color: #409eff;
      }
    }
    
    .chart-container {
      display: flex;
      
      .chart {
        width: 400px;
        height: 300px;
      }
      
      .stat-table {
        flex: 1;
        margin-left: 20px;
        max-width: 400px;
      }
    }
    
    .rate-stats {
      .rate-avg {
        margin-bottom: 20px;
        
        .rate-label {
          font-weight: bold;
          margin-right: 10px;
        }
      }
      
      .chart {
        width: 100%;
        height: 300px;
      }
    }
    
    .text-stats {
      .text-stats-header {
        margin-bottom: 10px;
        color: #606266;
      }
      
      .text-answers {
        background-color: #f5f7fa;
        padding: 10px;
        border-radius: 4px;
        
        .text-answer-item {
          padding: 10px;
          margin-bottom: 5px;
          background-color: #fff;
          border-radius: 4px;
          display: flex;
          
          .text-answer-index {
            width: 24px;
            height: 24px;
            line-height: 24px;
            text-align: center;
            background-color: #409eff;
            color: #fff;
            border-radius: 50%;
            margin-right: 10px;
            font-size: 12px;
          }
          
          .text-answer-content {
            flex: 1;
            line-height: 24px;
          }
        }
        
        .empty-answers {
          text-align: center;
          color: #909399;
          padding: 30px;
        }
      }
    }
  }
}

.empty-data {
  text-align: center;
  color: #909399;
  padding: 50px;
  font-size: 14px;
}

.loading-container {
  padding: 20px;
}
</style> 